import React from 'react';
import './myApplyList.less';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message ,Row,Col,DatePicker,Form,Checkbox,AutoComplete,InputNumber,Upload } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import getFormatDate from '../commonFunction/getFormatData';
import noRepeat from '../commonFunction/noRepeat';
import convertCurrency from '../commonFunction/convertCurrency';
import moment from 'moment';
const { TextArea } = Input;
const config = new Config();
const FormItem = Form.Item;
const Option = Select.Option;
const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const root = userInfo.root;
const { RangePicker } = DatePicker;
//新增申请的表单
class BannerForm1 extends React.Component {
    constructor(props){
        super(props);
        this.state={
            isBankCardPay:true,//是否是银行卡付款
            wordCount1:0,//申请事宜字数
            wordCount2:0,//付款项目字数
            selectionList:[[],[],[],[]],//所有筛选列表
            matchProducts:[],//产品自动完成列表
            matchProducts1:[],//平台自动完成列表
            selectValue:'',//产品自动完成列表选中的值
            selectValue1:'',//平台自动完成列表选中的值
            ModalAllDataUpdates:[{},{}],//模态框展示数据
            openingbankList:[],//开户行
            subbranchList:[],//支行
            accountList:[],//银行卡号
            cascader1:'',//级联
            cascader2:'',//级联
        }
    }
    //聚焦产品
    handleFocus(){
        this.setState({
            selectionList:this.props.selectionList,
            matchProducts:this.props.selectionList[0],//产品自动完成列表
            matchProducts1:this.props.selectionList[1],//平台自动完成列表
        })
    }
    //选择支付方式
    handlePayMethod(value){
        if(value==='1'){
            this.setState({
                isBankCardPay:false,
            })
        }else{
            this.setState({
                isBankCardPay:true,
            })
        }
    }
    //字数处理方法
    handleWordsCount(state,e){
        console.log();
        let value=e.target.value;
        if(value){
            if(state){
                this.setState({
                    wordCount1:value.length
                })
            }else{
                this.setState({
                    wordCount2:value.length
                })
            }
        }

    }
    //自动完成方法
    handleSearchMatchProducts(value){
        let {selectionList}=this.props;
        let projectNames = [];
        if(selectionList[0].length){
            selectionList[0].forEach(item=>{
                if(item.includes(value)){
                    projectNames.push(item);
                }
            });
        }
        this.setState({matchProducts:projectNames});
    }
    //自动完成方法
    handleSearchMatchProducts1(value){
        let {selectionList}=this.props;
        let projectNames = [];
        if(selectionList[1].length){
            selectionList[1].forEach(item=>{
                if(item.includes(value)){
                    projectNames.push(item);
                }
            });
        }
        this.setState({matchProducts1:projectNames});
    }
    //获得产品或平台输入的值
    handleOnChange(value){
        console.log(value);
        this.setState({
            selectValue:value,
        })
    }
    handleOnChange1(value){
        console.log(value);
        this.setState({
            selectValue1:value,
        })
    }
    //失去焦点
    handleBlue(){
        const {selectValue,selectValue1}=this.state;
        if(selectValue&&selectValue1){
           this.getApplyShowingData(selectValue,selectValue1,getFormatDate(new Date()));
        }

    }
    //生日禁用
    disabledDate(val) {
        if (val) {
            return val.valueOf() < Date.now();
        } else {
            return false;
        }
    }
    //获取申请展示数据
    getApplyShowingData(product, umbrellaname, time,){
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/findhistory`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                //user:sessionStorage.getItem('token'),
                product,//产品
                umbrellaname,//平台，渠道商
                requesttime:time,
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    this.setState({
                        ModalAllDataUpdates:data.data
                    },)
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //验证账户名是否重复
    handleNameDuplicate(value){
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/nameverification`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{ channelname:value},
            success: data => {
                console.log(data);
                if (data.code === 201) {
                    this.props.form.setFields({
                        channelname: { value: value,errors: [new Error(data.mes)] }
                    });
                }
            }
        });
    }
    //选择收款账户名触发的函数
    handleGetPaied(value){
        console.log(value);
        let {filesList}=this.props;
        let openingbankList=[];//开户行
        filesList.forEach(item=>{
            if(item.inforname===value){
                openingbankList.push(item.openingbank);
            }
        });
        this.setState({
            cascader1:value,
            openingbankList:noRepeat(openingbankList),
            subbranchList:[],
            accountList:[],
        });
        this.props.form.setFieldsValue({
            openingbank:undefined,//开户行
            subbranch:undefined,//支行
            account:undefined,//银行卡号
        });
    }
    //选择开户行
    handleGetPaied1(value){
        console.log(value);
        let {filesList}=this.props;
        let subbranchList=[];//支行
        filesList.forEach(item=>{
            if(item.inforname===this.state.cascader1&&item.openingbank===value){
                subbranchList.push(item.subbranch);
            }
        });
        this.setState({
            cascader2:value,
            subbranchList:noRepeat(subbranchList),
        });
        this.props.form.setFieldsValue({
            subbranch:undefined,//支行
            account:undefined,//银行卡号
        });
    }
    //选择支行
    handleGetPaied2(value){
        let {filesList}=this.props;
        let accountList=[];//银行卡号
        filesList.forEach(item=>{
            if(item.inforname===this.state.cascader1&&item.openingbank===this.state.cascader2&&item.subbranch===value){
                accountList.push(item.account);
            }
        });
        this.setState({
            accountList:noRepeat(accountList),
        });
    }
    render() {
        const { visible, saveBanner, handleCancel,form, normFile, beforeUpload, fileList, previewImg, previewVisible, cancelPreview, previewImage ,isLooking,filesList,filesListNames} =this.props;
        const {ModalAllDataUpdates, openingbankList,subbranchList,accountList}=this.state;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 }, };
        const formItemLayout1 = { labelCol: { span: 4 }, wrapperCol: { span: 20 }, };
        return (
            <Modal
                className="little-tool-modal"
                title="付款申请单"
                visible={visible}
                okText={isLooking?'确定':"提交申请"}
                cancelText={isLooking?'取消':"取消申请"}
                onOk={isLooking?handleCancel:saveBanner}
                onCancel={handleCancel}
                maskClosable={false}
            >
                <Form  >
                    <Row>
                        <Col span={7} offset={1}>
                            <FormItem {...formItemLayout} label="产品"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('product', {
                                    rules: [
                                        { required: true, message: '请输入产品名称' },
                                        { pattern: /^\S+$/, message: '请不要输入空格'}
                                    ],
                                })(
                                    <AutoComplete disabled={isLooking}
                                                  dataSource={this.state.matchProducts}
                                                  onSearch={this.handleSearchMatchProducts.bind(this)}
                                                  placeholder="请输入产品名称"
                                                  onChange={this.handleOnChange.bind(this)}
                                                  onBlur={this.handleBlue.bind(this)}
                                                  onFocus={this.handleFocus.bind(this)}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} offset={1}>
                            <FormItem {...formItemLayout} label="平台"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('umbrellaname', {
                                    rules: [{ required: true, message: '请输入平台' },
                                        { pattern: /^\S+$/, message: '请不要输入空格'}],
                                })(
                                    <AutoComplete disabled={isLooking}
                                                  dataSource={this.state.matchProducts1}
                                                  onSearch={this.handleSearchMatchProducts1.bind(this)}
                                                  placeholder="请输入平台"
                                                  onChange={this.handleOnChange1.bind(this)}
                                                  onBlur={this.handleBlue.bind(this)}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} offset={1}>
                            <FormItem {...formItemLayout} label="账户名"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('channelname', {
                                    rules: [{ required: true, message: '请输入账户名' },
                                        { pattern: /^\S+$/, message: '请不要输入空格'}],
                                })(
                                    <AutoComplete disabled={isLooking}
                                        placeholder="请输入账户名"
                                        onBlur={this.handleNameDuplicate.bind(this)}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <h3 className="my-apply-title">渠道商联系方式</h3>
                    <Row>
                        <Col span={11} offset={1}>
                            <FormItem {...formItemLayout1} label="姓名"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('name', {
                                    rules: [{ pattern: /^\S+$/, message: '请不要输入空格'}],
                                })(
                                    <Input placeholder="请输入姓名" disabled={isLooking}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11} offset={1}>
                            <FormItem {...formItemLayout1} label="手机号"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('phone', {
                                    rules: [{ pattern: /^(1[34578]\d{9})$/, message: '请输入正确的手机号' }]
                                })(
                                    <Input placeholder="请输入手机号" disabled={isLooking}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={23} offset={1}>
                            <FormItem {...{ labelCol: { span: 2 }, wrapperCol: { span: 22 }, }} label="公司名称"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('company', {
                                    rules: [{ pattern: /^\S+$/, message: '请不要输入空格'}],
                                })(
                                    <Input placeholder="请输入公司名称" disabled={isLooking}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <h3 className="my-apply-title">数据情况</h3>
                    <div style={{marginBottom:'20px',fontSize:'14px'}}>
                        <Row>
                            <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>近五天投放情况</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>消费：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0)}</Col>
                            <Col span={4}>总进线：</Col>
                            <Col span={4}>{ModalAllDataUpdates[0].coillnsum?ModalAllDataUpdates[0].coillnsum:0}</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>平均进线成本：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0)}</Col>
                            <Col span={4}>产出比：</Col>
                            <Col span={4}>{ModalAllDataUpdates[0].outputratio?ModalAllDataUpdates[0].outputratio:0}</Col>
                        </Row>
                        <Row>
                            <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>历史数据</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>消费：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0)}</Col>
                            <Col span={4}>总进线：</Col>
                            <Col span={4}>{ModalAllDataUpdates[1].coillnsum?ModalAllDataUpdates[1].coillnsum:0}</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>平均进线成本：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0)}</Col>
                            <Col span={4}>产出比：</Col>
                            <Col span={4}>{ModalAllDataUpdates[1].outputratio?ModalAllDataUpdates[1].outputratio:0}</Col>
                        </Row>
                    </div>
                    <h3 className="my-apply-title"><span style={{color:'red'}}>*</span>&nbsp;申请事宜（平台概述及销售主管投放建议）</h3>
                    <Row>
                        <Col span={23} offset={1} className="little-tool-textarea">
                            <FormItem {...{ labelCol: { span: 0 }, wrapperCol: { span: 24 }, }}>
                                {getFieldDecorator('affairs', {
                                    rules: [{ required: true, message: '请输入申请事宜' },
                                        { max:100,message: '请输入100字以内字符' }],
                                })(
                                    <TextArea  disabled={isLooking} placeholder="请输入申请事宜" autosize={{ minRows:4, maxRows: 6 }} onChange={this.handleWordsCount.bind(this,true)}/>
                                )}
                            </FormItem>
                            <div className="clearfix" style={{float:'right'}}>
                                <span style={{float:'right'}} >{this.state.wordCount1}/100</span>
                            </div>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} offset={1}>
                            <FormItem {...formItemLayout} label="收款账户名"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('inforname', {
                                    rules: [
                                        { required: true, message: '请选择收款账户名' }
                                    ],
                                })(
                                    <Select disabled={isLooking} placeholder="请选择收款账户名"  onChange={this.handleGetPaied.bind(this)}>
                                        {filesListNames.map(item=><Option value={item} key={item}>{item}</Option>)}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8} >
                            <FormItem {...formItemLayout} label="付款方式"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('paymethod', {
                                    rules: [
                                        { required: true, message: '请选择付款方式' }
                                    ],
                                    initialValue:'0'
                                })(
                                    <Select disabled={isLooking} onChange={this.handlePayMethod.bind(this)}>
                                        <Option value='0'>银行卡</Option>
                                        {/*<Option value='1'>支付宝</Option>*/}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} offset={1}>
                            <FormItem {...formItemLayout} label="开户行"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('openingbank', {
                                    rules: [
                                        {required: this.state.isBankCardPay?true:false, message: '请选择开户行' },
                                    ],
                                })(
                                    <Select disabled={isLooking} placeholder="请选择开户行" onChange={this.handleGetPaied1.bind(this)}>
                                        {openingbankList.map(item=><Option value={item} key={item}>{item}</Option>)}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8} >
                            <FormItem {...formItemLayout} label="支行"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('subbranch', {
                                    rules: [
                                        { required: this.state.isBankCardPay?true:false, message: '请选择支行' },
                                    ],
                                })(
                                    <Select disabled={isLooking} placeholder="请选择支行" onChange={this.handleGetPaied2.bind(this)}>
                                        {subbranchList.map(item=><Option value={item} key={item}>{item}</Option>)}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} >
                            <FormItem {...formItemLayout} label="银行卡号"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('account', {
                                    rules: [
                                        { required: true, message: '请选择银行卡号' },]
                                })(
                                    <Select disabled={isLooking} placeholder="请选择银行卡号">
                                        {accountList.map(item=><Option value={item} key={item}>{item}</Option>)}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={23} offset={1}>
                            <FormItem {...{ labelCol: { span: 2 }, wrapperCol: { span: 22 }, }} label="付款项目"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('payproject', {
                                    rules: [{ required: true, message: '请输入付款项目' },
                                        { max:50,message: '请输入50字以内字符' }],
                                })(
                                    <TextArea disabled={isLooking} placeholder="请输入付款项目" autosize={{ minRows:4, maxRows: 6 }} onChange={this.handleWordsCount.bind(this,false)}/>
                                )}
                            </FormItem>
                            <div className="clearfix" style={{float:'right'}}>
                                <span style={{float:'right'}} >{this.state.wordCount2}/50</span>
                            </div>
                        </Col>
                    </Row>
                    <Row style={{marginTop:'10px'}}>
                        <Col span={8} offset={1}>
                            <FormItem {...formItemLayout} label="付款金额"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('paymoney', {
                                    rules: [
                                        { required: true, message: '请输入付款金额' },]
                                })(
                                    <InputNumber disabled={isLooking} placeholder="请输入付款金额" style={{width:'100%'}} min={0} step={0.01} precision={2} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8} >
                            <FormItem {...formItemLayout} label="申请人"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('requestpeople', {
                                    rules: [
                                        { required: true, message: '请输入申请人' },
                                        { pattern: /^\S+$/, message: '请不要输入空格'}],
                                })(
                                    <Input disabled={isLooking} placeholder="请输入申请人"/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} >
                            <FormItem {...{ labelCol: { span: 10 }, wrapperCol: { span: 14 }, }} label="要求付款时间"  style={{ minHeight: '50px', marginBottom: 0 }}>
                                {getFieldDecorator('paytime', {
                                    rules: [{ required: true, message: '请选择付款时间' }],
                                })(
                                    <DatePicker disabled={isLooking}  format="YYYY-MM-DD"  disabledDate={(val) => this.disabledDate(val)}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} offset={1}>
                            <FormItem {...formItemLayout} label="填单拍照" style={{ minHeight: '120px', marginBottom: 0 }}>
                                {getFieldDecorator('Filedata', {
                                    valuePropName: 'fileList', getValueFromEvent: normFile,
                                    rules: [{ required: true, message: '请上传填单照片' }],
                                })(
                                    <Upload
                                        method="post"
                                        accept="image/*"
                                        name="Filedata"
                                        action={config.UploadFile + "/uploadpageimg"}
                                        beforeUpload={beforeUpload}
                                        listType="picture-card"
                                        className="upload-list-inline"
                                        onPreview={previewImg}
                                        showUploadList={{showPreviewIcon: true, showRemoveIcon: isLooking?false:true }}
                                    >
                                        {(fileList.length >= 5||isLooking) ?'':<div>
                                            <Icon type="plus" />
                                            <div className="ant-upload-text">点击上传图片</div>
                                        </div>}
                                    </Upload>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                {/* 预览图片对话框 */}
                <Modal visible={previewVisible} footer={null} onCancel={cancelPreview}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Modal>
        );
    }
}
const BannerForm = Form.create()(BannerForm1);

export default class MyApplyList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,//我的申请模态框
            applyList: [],//申请列表
            fileList: [],//图片列表
            previewVisible: false,//预览图片
            previewImage: '',//预览图片
            dateStr:['',''],//默认今天的日期字符串
            date:[undefined,undefined],//默认今天的日期
            selectedApplyState:'',//筛选状态
            selectedProduct:'',//筛选产品
            selectedUmbrellaName:'',//筛选平台
            applyPeopleName:'',//筛选负责人姓名
            record:{},//单条信息
            visible1: false, //查看模态框
            selectionList:[[],[],[],[]],//筛选列表
            alreadyGetSelectionList:false,//是否已经获取到筛选列表
            ModalAllDataUpdates:[{},{}],//模态框展示数据
            authTreeOfOne:{},//小工具权限
            filesList:[],//资料列表
            alreadyGetFilesList:false,//获得资料列表
            filesListNames:[],//资料列表名字
    }
    }
    componentWillMount(){
        console.log(userInfo.auth);
        if(userInfo.auth){
            if(userInfo.auth['橘色小工具']){
                this.setState({
                    authTreeOfOne:userInfo.auth['橘色小工具']
                },()=>{
                    console.log(this.state.authTreeOfOne['/payrequest/save']);
                })
            }
        }

    }
    componentDidMount() {
        this.getAllClassifyData();
        //初始化时间
        let dateStr=getFormatDate(new Date());
        this.setState({
            dateStr:[dateStr,dateStr],
            date:[moment(dateStr),moment(dateStr)],
        });
        this.getBannerList(JSON.stringify([dateStr,dateStr]));
        this.getFilesList();
    }
    //获取筛选列表
    getAllClassifyData(){
        //筛选列表
        let selectionList=[[],[],[],[]];
        const {authTreeOfOne}=this.state;
        let url='';
        if(authTreeOfOne['/payrequest/findonesource']){
            url=`${config.juseLittleTool}/payrequest/findonesource`
        }
        if(root||(authTreeOfOne['/payrequest/findsource'])){
            url=`${config.juseLittleTool}/payrequest/findsource`
        }
        $.ajax({
            url: url,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            //data:{ user:sessionStorage.getItem('token'),},
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const List = data.data;
                    if (List.length > 0) {
                        List.forEach((ele, i) => {
                            selectionList[0].push(ele.product);  //产品
                            selectionList[1].push(ele.umbrellaname);//平台
                            selectionList[2].push(ele.channelname);//账户名
                            selectionList[3].push(ele.requestpeople);//申请人
                        });
                        this.setState({
                            selectionList:[noRepeat(selectionList[0]),noRepeat(selectionList[1]),noRepeat(selectionList[2]),noRepeat(selectionList[3]),],
                            alreadyGetSelectionList:true,
                        },()=>{
                            console.log(this.state.selectionList);
                        })
                    }

                }
            }
        });
    }
    //获取文件管理列表
    getFilesList() {
        let url=`${config.juseLittleTool}/information/list`;
        $.ajax({
            url: url,
            type: "GET",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const filesList = data.data;
                    let arr=[];
                    if (filesList.length > 0) {
                        filesList.forEach((ele, i) => {
                            ele.index = i + 1;
                            arr.push(ele.inforname);
                        });
                        this.setState({
                            alreadyGetFilesList:true,
                            filesList,
                            filesListNames:noRepeat(arr)
                        },()=>{
                            console.log(666);
                            console.log(this.state.filesListNames);
                        });
                    }else{
                        this.setState({
                            filesList:[],
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //生日禁用
    disabledDate1(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }
    //日期筛选方法
    changeDate(date, dateStr) {
        this.setState({
            dateStr,
            date,
        });
        const{selectedApplyState,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        this.getBannerList(JSON.stringify(dateStr),selectedApplyState,selectedProduct,selectedUmbrellaName,applyPeopleName)
    }
    //获取申请展示数据
    getApplyShowingData1(product, umbrellaname, time,){
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/findhistory`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                product,//产品
                umbrellaname,//平台，渠道商
                requesttime:time,
                //user:sessionStorage.getItem('token'),
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    this.setState({
                        ModalAllDataUpdates:data.data
                    },)
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //筛选方法
    handleApplyState(state,value){
        console.log(state);
        const{dateStr,selectedApplyState,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        if(state===1){
            if(value){
                value=Number(value);
            }
            this.setState({
                selectedApplyState:value,
            });
            this.getBannerList(JSON.stringify(dateStr),value,selectedProduct,selectedUmbrellaName,applyPeopleName)
        }else if(state===2){
            this.setState({
                selectedProduct:value,
            });
            this.getBannerList(JSON.stringify(dateStr),selectedApplyState,value,selectedUmbrellaName,applyPeopleName)

        }else if(state===3){
            this.setState({
                selectedUmbrellaName:value,
            });
            this.getBannerList(JSON.stringify(dateStr),selectedApplyState,selectedProduct,value,applyPeopleName)
        }else{
            this.setState({
                applyPeopleName:value,
            });
            this.getBannerList(JSON.stringify(dateStr),selectedApplyState,selectedProduct,selectedUmbrellaName,value)
        }
    }
    //banner详细信息对话框（新增/编辑）
    showBannerModal(record) {
        if(record){
            this.setState({
                record,
                visible1: true, //查看模态框
            });
            this.getApplyShowingData1(record.product,record.umbrellaname,record.requesttime.slice(0,10));
        }else{
            this.setState({
                visible: true,
            });
        }
    }
    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        // let isLt10M = file.size / 1024 / 1024 < 10;
        // if (!isLt10M) {
        //     message.config({ top: 50 });
        //     message.error('您上传的图片大小必须小于10MB！');
        // }
        // return isIMG && isLt10M;
        return isIMG ;
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //获取表单元素
    saveBannerFormRef(form) {
        this.bannerForm = form;
    }
    //预览图片对话框
    previewImg(file){
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview(){
        this.setState({ previewVisible: false })
    }
    //取消，关闭对话框
    handleCancel() {
        this.bannerForm.resetFields();
        this.setState({
            visible: false,
            fileList: []
        });
    }
    //保存
    saveBanner() {
        this.bannerForm.validateFields((err, values)=>{
            if(err){
                return;
            }
            if(!err){
                console.log(values);
                if(values.paymethod==='0'){
                    if(!values.openingbank){
                        message.info('请先填写开户行',1);
                        return;
                    }
                    if(!values.subbranch){
                        message.info('请先填写支行',1);
                        return;
                    }
                }
                let imgURL=[];
                if(values.Filedata.length){
                    values.Filedata.forEach(item=>{
                        imgURL.push(item.response ? item.response.name : item.name);
                    })
                }
                console.log(imgURL);
                let url=`${config.juseLittleTool}/payrequest/save`;
                let  data={
                     product : values.product,//产品
                     umbrellaname : values.umbrellaname,//平台
                     channelname : values.channelname,//账户名称
                     name : values.name,//平台姓名
                     company : values.company,//公司名称
                     phone : values.phone,//手机号
                     affairs : values.affairs,//申请事宜说明
                     paymethod : values.paymethod,//付款方式
                     openingbank : values.openingbank,//开户行
                     subbranch : values.subbranch,//支行
                     account : values.account,//账号（媒介自定义）
                     paytime : values.paytime? values.paytime.format('YYYY-MM-DD'):undefined,//要求付款时间
                     payproject : values.payproject,//付款项目
                     paymoney : values.paymoney,//付款金额
                     requestpeople : values.requestpeople,//申请人
                     inforname : values.inforname,//收款人账号
                     imgURL:JSON.stringify(imgURL),//图片路径

                     };
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data: data,
                    success: res => {
                        console.log(res);
                        if(res.code === 200){
                            this.setState({
                                visible: false,
                                fileList: []
                            },
                                ()=>{
                                    let dateStr=getFormatDate(new Date());
                                    this.setState({
                                        dateStr:[dateStr,dateStr],
                                        date:[moment(dateStr),moment(dateStr)],
                                    });
                                this.getBannerList(JSON.stringify([dateStr,dateStr]));
                                this.getAllClassifyData();
                            }
                            );
                            this.bannerForm.resetFields();
                        }else if(res.code===201){
                            this.bannerForm.setFields({
                                channelname: { value:  values.channelname,errors: [new Error(res.mes)] }
                            });
                            Modal.warning({
                                title: '保存失败',
                                content: `${res.mes}请返回重新操作`,
                            });
                        }else{
                            Modal.warning({
                                title: '保存失败',
                                content: `${res.mes}请返回重新操作`,
                            });
                        }
                    }
                });
            }
        })
    }
     //获取申请列表
    getBannerList(time,state,product,budget,people) {
        const {authTreeOfOne}=this.state;
        let url='';
        if(authTreeOfOne['/payrequest/findonelist']){
            url=`${config.juseLittleTool}/payrequest/findonelist`
        }
        if(root||(authTreeOfOne['/payrequest/findlist'])){
            url=`${config.juseLittleTool}/payrequest/findlist`
        }
        $.ajax({
            url:url,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                 pagesize:100,
                 pageindex:1,
                 requesttime:time,
                 state,//申请状态
                 product,//产品
                 budget,//平台
                 people,//申请人
                 //user:sessionStorage.getItem('token'),
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const applyList = data.data.rows;
                    if (applyList.length > 0) {
                        applyList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                        this.setState({
                            applyList,
                            applycount: data.data.count,
                        });
                    }else{
                        this.setState({
                            applyList:[],
                            applycount: 0,
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //筛选查询
    doSearch(){
        const{dateStr,selectedApplyState,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        this.getBannerList(JSON.stringify(dateStr),selectedApplyState,selectedProduct,selectedUmbrellaName,applyPeopleName)
    }
    render() {
        const{record,selectionList,ModalAllDataUpdates,authTreeOfOne}=this.state;
        const columns = [
            {
                title: '申请时间',
                dataIndex: 'requesttime',
                width:150,
            },
            {
                title: '审批时间',
                dataIndex: 'examinetime',
                width: 150,
            }, {
                title: '拨款时间',
                dataIndex: 'appropriationtime',
                width: 150,
            },{
                title: '产品',
                dataIndex: 'product',
                width: 100,
            }, {
                title: '平台',
                dataIndex: 'umbrellaname',
                width: 100,
            }, {
                title: '账户名',
                dataIndex: 'channelname',
                width: 100
            }, {
                title: '付款类型',
                dataIndex: 'paymethod',
                width: 100,
                render:text=><span>{text==='0'?'银行卡':'支付宝'}</span>
            }, {
                title: '申请状态',
                dataIndex: 'approvalstatus',
                width: 100,
                render:text=><span style={{color:text===1?'':text===3?'green':text===4?'red':''}}>{text===1?'申请中':text===2?'已通过':text===3?'已拨款':text===4?'已驳回':''}</span>
            }, {
                title: '申请人',
                dataIndex: 'requestpeople',
                width: 100
            }, {
                title: '操作',
                width: 100,
                render: (text, record) => (
                    <div>
                        <Button  type="primary" onClick={() => this.showBannerModal(record)}>查看</Button>
                    </div>
                )
            }
        ];
        return (
            <div className='goods-label clearfix'>
                {/*面包屑*/}
                < Breadcrumb separator=">" >
                    <Breadcrumb.Item>橘色小工具</Breadcrumb.Item>
                    <Breadcrumb.Item>我的申请</Breadcrumb.Item>
                    <Breadcrumb.Item>费用申请</Breadcrumb.Item>
                </Breadcrumb >
                {/*筛选条*/}
                <div style={{marginTop:'40px'}}>
                    <Row>
                        <Col span={6}>
                            申请时间:&nbsp;&nbsp;&nbsp;
                            <RangePicker placeholder={['请选择日期', '请选择日期']}
                                         onChange={this.changeDate.bind(this)}
                                         format='YYYY-MM-DD'
                                         value={this.state.date}
                                         style={{width:'180px'}}
                                         disabledDate={(val) => this.disabledDate1(val)}
                            />
                        </Col>
                        <Col span={5}>
                            申请状态:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'150px'}} onChange={this.handleApplyState.bind(this,1)} defaultValue="">
                                <Option value='' >全部</Option>
                                <Option value='1' >申请中</Option>
                                <Option value='2' >已通过</Option>
                                <Option value='3' >已拨款</Option>
                                <Option value='4' >已驳回</Option>
                            </Select>
                        </Col>
                        <Col span={4}>
                            产品:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'120px'}} onChange={this.handleApplyState.bind(this,2)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[0].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={4}>
                            平台:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'120px'}} onChange={this.handleApplyState.bind(this,3)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[1].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={4}>
                            申请人:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'120px'}} onChange={this.handleApplyState.bind(this,4)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[3].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={1}>
                            <Button type="primary" onClick={this.doSearch.bind(this)}>查询</Button>
                        </Col>
                    </Row>
                </div>
                <div className='allgoods-table clearfix' style={{marginTop:'40px'}}>
                    <Table
                        rowKey="index"
                        className="floor-table"
                        columns={columns}
                        dataSource={this.state.applyList}
                        pagination={false}
                        bordered
                    />
                </div>
                {(root)||(authTreeOfOne['/payrequest/save'])?<div style={{textAlign:'center'}}>
                    <Button type="primary" size="large" style={{width:'100%',marginTop:'50px'}} onClick={() => this.showBannerModal()}>发起申请+</Button>
                </div>:''}
                <BannerForm
                    visible={this.state.visible}
                    saveBanner={this.saveBanner.bind(this)}
                    handleCancel={this.handleCancel.bind(this)}
                    ref={this.saveBannerFormRef.bind(this)}
                    normFile={this.normFile.bind(this)}
                    beforeUpload={this.beforeUpload.bind(this)}
                    fileList={this.state.fileList}
                    previewImg={this.previewImg.bind(this)}
                    previewVisible={this.state.previewVisible}
                    cancelPreview={this.cancelPreview.bind(this)}
                    previewImage={this.state.previewImage}
                    isLooking={this.state.isLooking}
                    selectionList={this.state.alreadyGetSelectionList?this.state.selectionList:[[],[],[],[]]}
                    filesList={this.state.alreadyGetFilesList?this.state.filesList:[]}
                    filesListNames={this.state.alreadyGetFilesList?this.state.filesListNames:[]}
                />
                <Modal
                    className="little-tool-modal-middle"
                    title="付款申请单"
                    visible={this.state.visible1}
                    onCancel={()=>{this.setState({visible1:false,})}}
                    footer={null}
                    maskClosable={false}
                >
                    <Row>
                        <Col span={7} offset={1}>
                            产品：{record.product}
                        </Col>
                        <Col span={7} offset={1}>
                            平台：{record.umbrellaname}
                        </Col>
                        <Col span={7} offset={1}>
                            账户名:{record.channelname}
                        </Col>
                    </Row>
                    <h3 className="my-apply-title-middle">平台联系方式</h3>
                    <Row>
                        <Col span={11} offset={1}>
                            姓名:{record.name?record.name:' --'}
                        </Col>
                        <Col span={11} offset={1}>
                            手机号码:{record.phone?record.phone:' --'}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={23} offset={1}>
                            公司名称:{record.company?record.company:' --'}
                        </Col>
                    </Row>
                    <h3 className="my-apply-title-middle">数据情况</h3>
                    <div >
                        <Row>
                            <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>近五天投放情况</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>消费：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0)}</Col>
                            <Col span={4}>总进线：</Col>
                            <Col span={4}>{ModalAllDataUpdates[0].coillnsum?ModalAllDataUpdates[0].coillnsum:0}</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>平均进线成本：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0)}</Col>
                            <Col span={4}>产出比：</Col>
                            <Col span={4}>{ModalAllDataUpdates[0].outputratio?ModalAllDataUpdates[0].outputratio:0}</Col>
                        </Row>
                        <Row>
                            <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>历史数据</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>消费：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0)}</Col>
                            <Col span={4}>总进线：</Col>
                            <Col span={4}>{ModalAllDataUpdates[1].coillnsum?ModalAllDataUpdates[1].coillnsum:0}</Col>
                        </Row>
                        <Row>
                            <Col span={4} offset={1}>平均进线成本：</Col>
                            <Col span={3} >￥{ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0}</Col>
                            <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0)}</Col>
                            <Col span={4}>产出比：</Col>
                            <Col span={4}>{ModalAllDataUpdates[1].outputratio?ModalAllDataUpdates[1].outputratio:0}</Col>
                        </Row>
                    </div>
                    <h3 className="my-apply-title-middle">申请事宜（平台概述及销售主管投放建议）</h3>
                    <Row>
                        <Col span={22} offset={1} className="little-tool-textarea" style={{background:'#ddd',padding:'5px',borderRadius:'5px'}}>
                            {record.affairs}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} offset={1}>
                            收款账户名：{record.inforname}
                        </Col>
                        <Col span={8} >
                            付款方式：{record.paymethod==0?'银行卡':'支付宝'}
                        </Col>

                    </Row>
                    <Row>
                        <Col span={8} offset={1}>
                            开户行:{record.openingbank}
                        </Col>
                        <Col span={7} >
                            支行:{record.subbranch}
                        </Col>
                        <Col span={8} >
                            银行卡号：{record.account}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={23} offset={1}>
                            付款项目：{record.payproject}
                        </Col>
                    </Row>
                    <Row style={{marginTop:'10px'}}>
                        <Col span={8} offset={1}>
                            付款金额：{record.paymoney}
                        </Col>
                        <Col span={7} >
                            申请人：{record.requestpeople}
                        </Col>
                        <Col  span={8} >
                            要求付款时间: {record.paytime}
                        </Col>
                    </Row>
                    <Row>
                        <Col span={23} offset={1}>
                            <p>填单拍照：</p>
                            {
                            record.imgURL?(JSON.parse(record.imgURL)).length ? (JSON.parse(record.imgURL)).map((item,i)=>{
                                return <a href={config.Filepath + item} target="_blank" key={i} style={{marginRight:'20px'}}>
                                    <img src={config.Filepath +item} style={{ height: "100px", width: "200px" }} />
                                </a>
                            }):'未上传图片':''
                        }
                        </Col>
                    </Row>
                    {record.approvalstatus==3?<Row>
                        <Col span={23} offset={1}>
                            <p>拨款凭据照片：</p>
                            {/*<div className="gallery">*/}
                                {
                                    record.appropriationimg?(JSON.parse(record.appropriationimg)).length ? (JSON.parse(record.appropriationimg)).map((item,i)=>{
                                        return <a href={config.Filepath + item} target="_blank" key={i} style={{marginRight:'20px'}}>
                                            <img  src={config.Filepath +item} style={{ height: "100px", width: "200px" }} />
                                        </a>
                                    }):<span>未上传凭证</span>:<span>未上传凭证</span>
                                }
                            {/*</div>*/}

                        </Col>
                    </Row>:''}

                    <div style={{textAlign:'center'}}>
                        <Button onClick={()=>{this.setState({visible1:false,})}}>取消</Button>
                    </div>
                </Modal>
            </div>
        )
    }
}